package api

import (
	"github.com/gin-gonic/gin"
	"server/global"
	"server/internal/middleware"
	"server/internal/model"
	"server/internal/pkg/response"
	"server/internal/services"
	"server/utils/tools"
	"strings"
)

// GroupApi 角色管理
var GroupApi = new(groupApi)

type groupApi struct {
	model.UserGroup
}

// Router 路由
func (a groupApi) Router(r *gin.RouterGroup) {
	api := r.Group("/user_group", middleware.LoginVerification, middleware.PermissionVerification)
	//验证权限
	api.GET("/list", a.list)
	api.GET("/edit", a.detail)
	api.POST("/add", a.add)
	api.POST("/edit", a.edit)
	api.POST("/del", a.del)
	api.GET("/get_group", a.getGroup)

	//不验证权限
	api2 := r.Group("/user_group", middleware.LoginVerification)
	api2.GET("/get_select", a.getSelect)

}

// List 列表
func (groupApi) list(c *gin.Context) {
	Db := global.GL_DB

	list, _ := services.UserGroup.GetList(Db) //树状图
	response.SuccessList(c, list, 0)
}

// Detail 单条
func (groupApi) detail(c *gin.Context) {
	id := c.Query("id")

	detail := services.UserGroup.GetById(id)
	response.SuccessData(c, detail, "")
}

// Detail 单条
func (groupApi) getGroup(c *gin.Context) {
	id := c.Query("id")

	detail := services.UserGroup.GetById(id)
	group := strings.Split(detail.Rules, ",")

	response.SuccessData(c, tools.StringArrToIntArr(group), "")
}

// Add 添加
func (a groupApi) add(c *gin.Context) {
	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	if _, err := services.UserGroup.Create(a.UserGroup); err == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Error(c, "添加失败")
	}
}

// Edit 编辑
func (a groupApi) edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	//7为普通用户 不可编辑
	if a.ID == 7 {
		response.Error(c, "固定分组无法编辑")
		return
	}

	if _, err := services.UserGroup.Update(a.UserGroup); err == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Error(c, "编辑失败")
	}
}

// Del 删除
func (groupApi) del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	for _, v := range param.Ids {

		if v == 1 {
			response.Error(c, "超级管理员无法删除")
			return
		}
		if v == 2 {
			response.Error(c, "固定角色无法删除")
			return
		}
		if v == 3 {
			response.Error(c, "固定角色无法删除")
			return
		}
	}

	if services.UserGroup.Delete(param.Ids) == nil {
		response.Success(c, "", "删除成功")
	} else {
		response.Error(c, "删除失败")
	}
}

// GetSelect 列表
func (groupApi) getSelect(c *gin.Context) {
	Db := global.GL_DB
	rules, _ := c.Get("rules")
	if rules.(string) != "*" {
		Db = Db.Where("id<>?", 1)
	}

	list, _ := services.UserGroup.GetList(Db) //树状图
	response.SuccessList(c, list, 0)
}
